package com.ai.service.impl;

import com.ai.entity.SysUserRoleEntity;
import com.ai.mapper.SysUserRoleMapper;
import com.ai.service.UserRoleService;
import com.ai.web.request.UserRoleOperationReqVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户角色表
 */
@Service
public class UserRoleServiceImpl  implements UserRoleService {

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public List<String> getRoleIdsByUserId(String userId) {
        List<SysUserRoleEntity> sysUserRoles = sysUserRoleMapper.selectList(Wrappers.<SysUserRoleEntity>lambdaQuery().select(SysUserRoleEntity::getRoleId).eq(SysUserRoleEntity::getUserId, userId));
        return sysUserRoles.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
    }


    @Override
    public void addUserRoleInfo(UserRoleOperationReqVO vo) {
        addUserRole(vo.getUserId(),vo.getRoleIds());
    }

    @Override
    public void addUserRole(String userId, List<String> roleIds) {
        if (!CollectionUtils.isEmpty(roleIds)) {
            LambdaQueryWrapper<SysUserRoleEntity> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(SysUserRoleEntity::getUserId, userId);
            sysUserRoleMapper.delete(queryWrapper);

            roleIds.forEach(e->{
                SysUserRoleEntity sysUserRole=new SysUserRoleEntity();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(e);
                sysUserRoleMapper.insert(sysUserRole);
            });

        }
    }
}
